import React from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Form,
  Select,
  Input,
  Radio,
  Checkbox,
  Button,
  TimePicker,
  TreeSelect,
  DatePicker,
  InputNumber,
  Alert,
} from 'antd';
import { ruleP, nameMinLength, nameMaxLength } from '@/utils/rule';
import moment from 'moment';

@connect(
  state => ({
    loadingqueryResExecutionCycleTypeList:
      state.loading.effects['taskMngt/queryResExecutionCycleTypeList'],
    loadingqueryList: state.loading.effects['taskMngt/queryList'],
    dataqueryResExecutionCycleTypeList: state.taskMngt.dataqueryResExecutionCycleTypeList,
    dataqueryList: state.taskMngt.dataqueryList,
  }),
  dispatch => ({
    queryResExecutionCycleTypeList: e =>
      dispatch({ type: 'taskMngt/queryResExecutionCycleTypeList', payload: e }),
    queryList: e => dispatch({ type: 'taskMngt/queryList', payload: e }),
  })
)
@Form.create({ name: 'basicInformation' })
export default class BasicInformation extends React.Component {
  static defaultProps = {
    initialData: {},
  };
  componentDidMount() {
    this.props.queryResExecutionCycleTypeList();
    this.props.getInstance(this);
    // this.props.queryOrgUserTree(); //获取可见范围的人
    this.props.queryList({status:0});
  }
  render() {
    return (
      <Form labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
        <Form.Item label="任务名称">
          {this.props.form.getFieldDecorator('executionPolicyName', {
            rules: [
              {
                required: true,
                whitespace: true, 
                message: '任务名称不能为空',
              },             
              { max: nameMaxLength()[0], message: nameMaxLength()[1] },
              { min: nameMinLength()[0], message: nameMinLength()[1] },
            ],
            initialValue: this.props.initialData.executionPolicyName,
          })(<Input allowClear placeholder="请输入" />)}
        </Form.Item>
        {/* <Form.Item label="任务类型"
        help={this.props.form.getFieldValue('executionPolicyType') == 1?'说明：第一次为全量扫描，后续为增量扫描。':''}
        >
          {this.props.form.getFieldDecorator('executionPolicyType', {
            rules: [
              {
                required: true,
                message: '请选择任务类型',
              },
            ],
            initialValue: this.props.initialData.executionPolicyType,
          })(
            <Select disabled={Boolean(this.props.initialData.executionPolicyType)} allowClear placeholder="请选择">
              {[
                { executionPolicyType: 1, auditTaskTypeName: '全量/增量' },
                { executionPolicyType: 2, auditTaskTypeName: '抽样' },
              ].map(item => (
                <Select.Option key={item.executionPolicyType} value={item.executionPolicyType}>
                  {item.auditTaskTypeName}
                </Select.Option>
              ))}
            </Select>
          )}
        </Form.Item>      */}

      <Form.Item label="任务类型" style={{display:'none'}}>
          {this.props.form.getFieldDecorator('executionPolicyType', {            
            initialValue: 2,
          })(
            <Select placeholder="请选择">
              {[
                { executionPolicyType: 1, auditTaskTypeName: '全量/增量' },
                { executionPolicyType: 2, auditTaskTypeName: '抽样' },
              ].map(item => (
                <Select.Option key={item.executionPolicyType} value={item.executionPolicyType}>
                  {item.auditTaskTypeName}
                </Select.Option>
              ))}
            </Select>
          )}
        </Form.Item>  

        {this.props.form.getFieldValue('executionPolicyType') == 2 ? (
          <Form.Item label="行数">
            {this.props.form.getFieldDecorator('lineNumber', {
              rules: [
                {
                  required: true,
                  message: '请输入行数',
                },
              ],
              initialValue: this.props.initialData.lineNumber,
            })(
              <InputNumber
                placeholder="请输入行数"
                style={{ width: '65%' }}
                max={1000}
                min={1}
                allowClear
              />
            )}
            <span className="ant-form-text" style={{color:'#999'}}>&nbsp;&nbsp;数值范围：1-1000</span>
          </Form.Item>
        ) : null}
        <Form.Item label="执行周期">
          {/* {this.props.form.getFieldDecorator('executionDay', {
            rules: [
              {
                required: true,
              },
            ],
          })( */}
          <Row gutter={8}>
            <Col span={8}>
              <Form.Item>
                {this.props.form.getFieldDecorator('executionCycleTypeId', {
                  rules: [
                    {
                      required: true,
                      message: '请选择执行周期',
                    },
                  ],
                  initialValue: this.props.initialData.executionCycleTypeId,
                })(
                  <Select
                    style={{ width: '100%' }}
                    placeholder="请选择执行周期"
                    loading={this.props.loadingqueryResExecutionCycleTypeList}
                    onChange={() =>
                      setTimeout(() =>
                        this.props.form.setFieldsValue({
                          executionTime: undefined,
                          executionDay: undefined,
                        })
                      )
                    }
                  >
                    {[
                      {
                        cycleTypeId: 1,
                        cycleTypeCode: 'NOW_PERFORM',
                        cycleTypeName: '立即执行',
                      },
                      {
                        cycleTypeId: 2,
                        cycleTypeCode: 'TIMING_PERFORM',
                        cycleTypeName: '定时执行',
                      },
                      {
                        cycleTypeId: 4,
                        cycleTypeCode: 'WEEK_PERFORM',
                        cycleTypeName: '按周执行',
                      },
                      {
                        cycleTypeId: 5,
                        cycleTypeCode: 'MONTH_PERFORM',
                        cycleTypeName: '按月执行',
                      },
                      {
                        cycleTypeId: 7,
                        cycleTypeCode: 'PERIODIC_PERFORM',
                        cycleTypeName: '周期执行',
                      },
                    ].map(item => (
                      <Select.Option key={item.cycleTypeId} value={item.cycleTypeId}>
                        {item.cycleTypeName}
                      </Select.Option>
                    ))}
                  </Select>
                )}
              </Form.Item>
            </Col>
            {/* 每周执行 */}
            {[4].includes(this.props.form.getFieldValue('executionCycleTypeId')) ? (
              <Col span={8}>
                <Form.Item>
                  {this.props.form.getFieldDecorator('executionDay', {
                    rules: [
                      {
                        required: true,
                        message: '请选择执行日期',
                      },
                    ],
                    initialValue: this.props.initialData.executionDay,
                  })(
                    <Select
                      style={{ width: '100%' }}
                      allowClear
                      placeholder="请选择执行日期"
                      loading={this.props.loadingqueryResExecutionCycleTypeList}
                    >
                      {[
                        { title: '星期日', value: 0 },
                        { title: '星期一', value: 1 },
                        { title: '星期二', value: 2 },
                        { title: '星期三', value: 3 },
                        { title: '星期四', value: 4 },
                        { title: '星期五', value: 5 },
                        { title: '星期六', value: 6 },
                      ].map(item => (
                        <Select.Option key={item.value} value={item.value} allowClear>
                          {item.title}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            ) : null}
            {/* 每月执行 */}
            {[5].includes(this.props.form.getFieldValue('executionCycleTypeId')) ? (
              <Col span={8}>
                <Form.Item>
                  {this.props.form.getFieldDecorator('executionDay', {
                    rules: [
                      {
                        required: true,
                        message: '请输入执行日期',
                      },
                    ],
                    initialValue: this.props.initialData.executionDay,
                  })(
                    <InputNumber
                      placeholder="请输入日期"
                      style={{ width: '100%' }}
                      max={31}
                      min={1}
                      allowClear
                    />
                  )}
                </Form.Item>
              </Col>
            ) : null}
            {/* 定时执行 */}
            {[2].includes(this.props.form.getFieldValue('executionCycleTypeId')) ? (
              <Col span={8}>
                <Form.Item>
                  {this.props.form.getFieldDecorator('executionTime', {
                    rules: [
                      {
                        required: true,
                        message: '请选择执行时间',
                      },
                      {
                        validator: (rule, value, callback) => {
                          moment().isBefore(value) ? callback() : callback(rule.message);
                        },
                        message: '时间应该大于当前时间',
                      },
                    ],
                    initialValue:
                      (this.props.initialData.executionTime &&
                        moment(this.props.initialData.executionTime).isValid() &&
                        moment(this.props.initialData.executionTime)) ||
                      undefined,
                  })(
                    <DatePicker
                      style={{ width: '100%' }}
                      showTime
                      allowClear
                      disabledDate={current => current && current < moment().subtract(1, 'day')}
                      // disabledTime={() => ({
                      //   disabledHours: () =>
                      //     new Array(moment().add(5, 'minutes').hours()).fill().map((item, index) => index),
                      //   disabledMinutes: () =>
                      //     new Array(moment().add(5, 'minutes').minutes()).fill().map((item, index) => index),
                      //   disabledSeconds: () =>
                      //     new Array(moment().seconds()).fill().map((item, index) => index),
                      // })}
                    />
                  )}
                </Form.Item>
              </Col>
            ) : null}
            {/* 每季执行 */}
            {[6].includes(this.props.form.getFieldValue('executionCycleTypeId')) ? (
              <Col span={8}>
                <Form.Item>
                  {this.props.form.getFieldDecorator('executionDay', {
                    rules: [
                      {
                        required: true,
                        message: '请输入每个季度的第几天',
                      },
                    ],
                    initialValue: this.props.initialData.executionDay,
                  })(
                    <InputNumber
                      placeholder="请输入每个季度的第几天"
                      style={{ width: '100%' }}
                      max={92}
                      min={1}
                      allowClear
                    />
                  )}
                </Form.Item>
              </Col>
            ) : null}
            {/* 周期执行 */}
            {[7].includes(this.props.form.getFieldValue('executionCycleTypeId')) ? (
              <Col span={8}>
                <Form.Item>
                  {this.props.form.getFieldDecorator('executionDay', {
                    rules: [
                      {
                        required: true,
                        message: '请输入周期天数',
                      },
                    ],
                    initialValue: this.props.initialData.executionDay,
                  })(
                    <InputNumber
                      placeholder="请输入周期天数"
                      style={{ width: '100%' }}
                      min={1}
                      max={365}
                      allowClear
                    />
                  )}
                </Form.Item>
              </Col>
            ) : null}
            {/* 每日执行、每周执行、每月执行、每季执行、周期执行 */}
            {[3, 4, 5, 6, 7].includes(this.props.form.getFieldValue('executionCycleTypeId')) ? (
              <Col span={8}>
                <Form.Item>
                  {this.props.form.getFieldDecorator('executionTime', {
                    rules: [
                      {
                        required: true,
                        message: '请选择执行时间',
                      },
                    ],
                    initialValue:
                      this.props.initialData.executionTime &&
                      moment(this.props.initialData.executionTime, 'HH:mm'),
                  })(<TimePicker format="HH:mm" style={{ width: '100%' }} allowClear />)}
                </Form.Item>
              </Col>
            ) : null}
          </Row>

          {/* )} */}
        </Form.Item>

        {/* <Form.Item label="用户范围">
          {this.props.form.getFieldDecorator('resAuditTaskUserScopePos', {
            rules: [
              {
                required: true,
                message: '请选择用户',
              },
            ],
            initialValue: this.props.initialData.resAuditTaskUserScopePos,
          })(
            <TreeSelect
              allowClear
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              multiple
              treeNodeFilterProp="title"
              treeCheckable
              showSearch
            >
              {loopfuzeren(this.props.dataqueryOrgUserTree)}
            </TreeSelect>
          )}
        </Form.Item> */}

        <Form.Item label="资源范围">
          {this.props.form.getFieldDecorator('restaskDbGroupPos', {
            rules: [
              {
                required: true,
                message: '请选择资源范围',
              },
            ],
            initialValue:
              this.props.initialData.taskDbGroupPos &&
              this.props.initialData.taskDbGroupPos.map(item =>
                JSON.stringify({ dbGroupTypeId: item.dbGroupTypeId, dbGroupId: item.dbGroupId, })
              ),
          })(
            <TreeSelect
              allowClear
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              multiple
              treeNodeFilterProp="title"
              showCheckedStrategy={TreeSelect.SHOW_PARENT}
              treeCheckable
              showSearch
              placeholder="请选择"
            >
              {loopGroupTree(this.props.dataqueryList)}
            </TreeSelect>
          )}
        </Form.Item>
        <Form.Item label="是否开启">
          {this.props.form.getFieldDecorator('taskStatus', {
            rules: [
              {
                required: true,
                message: '请选择是否开启',
              },
            ],
            initialValue: this.props.initialData.taskStatus || 0,
          })(
            <Radio.Group>
              <Radio value={0}>启用</Radio>
              <Radio value={1}>停用</Radio>
            </Radio.Group>
          )}
        </Form.Item>
      </Form>
    );
  }
}

const loopfuzeren = data => {
  return data.map(item => {
    if (item ? item.children && item.children.length : '') {
      return (
        <TreeSelect.TreeNode
          key={item.orgCode}
          checkable={false}
          value={item.orgCode}
          title={item.orgName}
        >
          {loopfuzeren(item.children)}
        </TreeSelect.TreeNode>
      );
    } else if (item.orgCode) {
      return (
        <TreeSelect.TreeNode
          key={item.orgCode}
          checkable={false}
          value={item.orgCode}
          title={item.orgName}
        ></TreeSelect.TreeNode>
      );
    }
    return (
      <TreeSelect.TreeNode
        isLeaf
        key={item.userCode}
        value={JSON.stringify({ userId: item.userId, userCode: item.userCode })}
        title={item.userName}
      />
    );
  });
};

const loopGroupTree = data => {
  return data.map(item => {
    if (item.children) {
      return (
        <TreeSelect.TreeNode
          key={item.id}
          value={JSON.stringify({ dbGroupTypeId: 0, dbGroupId: item.id })}
          title={item.groupName}
        >
          {loopGroupTree(item.children)}
        </TreeSelect.TreeNode>
      );
    }
    return (
      <TreeSelect.TreeNode
        key={item.id}
        value={JSON.stringify({ dbGroupTypeId: 0, dbGroupId: item.id })}
        title={item.groupName}
      />
    );
  });
};
